---
import { buttonVariants } from "@/components/ui/Button";
import { docsConfig } from "@/config/docs";
import { cn } from "@/lib/utils";
import { Icon } from "astro-icon/components";
import type { CollectionEntry } from "astro:content";

type Props = {
  slug: CollectionEntry<"docs">["slug"];
};

export function getPagerForDoc(slug: string) {
  const flattenedLinks = [...flatten(docsConfig.sidebarNav)];
  let activeIndex = flattenedLinks.findIndex(
    (link) => `/docs/${slug}` === link?.href,
  );

  activeIndex = Math.max(activeIndex, 0);
  const prev = activeIndex !== 0 ? flattenedLinks[activeIndex - 1] : null;
  const next =
    activeIndex !== flattenedLinks.length - 1
      ? flattenedLinks[activeIndex + 1]
      : null;
  return {
    prev,
    next,
  };
}

// @ts-ignore
export function flatten(links: { items? }[]) {
  return links.reduce((flat, link) => {
    return flat.concat(link.items ? flatten(link.items) : link);
  }, []);
}

const { slug } = Astro.props;
const pager = getPagerForDoc(slug);

if (!pager) {
  return null;
}
---

<div class="flex flex-row items-center justify-between">
  {
    pager?.prev && (
      <a
        href={pager.prev.href}
        class={cn(buttonVariants({ variant: "outline" }))}
      >
        <Icon name="lucide:chevron-left" class="mr-2 size-4" />

        {pager.prev.title}
      </a>
    )
  }
  {
    pager?.next && (
      <a
        href={pager.next.href}
        class={cn(buttonVariants({ variant: "outline" }), "ml-auto")}
      >
        {pager.next.title}
        <Icon name="lucide:chevron-right" class="ml-2 size-4" />
      </a>
    )
  }
</div>
